package cn.chen.算法.十算法;

// 暴力匹配算法
public class BruteForceAlgorithm {

    public static void main(String[] args) {

        String str1="java java i like java do you like  i like java";
        String str2="a i like java d";
        int index = bruteForce(str1, str2);
        System.out.println(index);
    }
    // 暴力匹配算法的实现
    public static int bruteForce(String str1, String str2) {

        char[] s1 = str1.toCharArray();
        char[] s2 = str2.toCharArray();

        int s1Len = s1.length;
        int s2Len = s2.length;
        int i = 0, j = 0;    // i直线str1，j指向str2

        while (i < s1Len && j < s2Len) {

            if(s1[i]==s2[j]){

                i++;
                j++;
            }
            else {

                i=i-(j-1);
                j=0;
            }
        }

        // 判断是否匹配成功
        if(j==s2Len)        // 匹配成功

            return i-j;
        else                // 匹配失败
            return -1;
    }
}
